#pragma once
#include <iostream>
#include "Protocol.hpp"

enum{
    DIV_ZERO = 1,
    MOD_ZERO,
    OTHER_OPER
};

class ServerCal
{
public:
    ServerCal() {}

    Response CalculatorHandler(const Request& req)
    {
        Response resp(0, 0);
        switch (req.op)
        {
        case '+':
            resp.result = req.x + req.y;
            break;
        case '-':
            resp.result = req.x - req.y;
            break;
        case '*':
            resp.result = req.x * req.y;
            break;
        case '/':
            {
                if(req.y == 0) resp.code = DIV_ZERO;
                else resp.result = req.x / req.y;
            }
            break;
        case '%':
            {
                if(req.y == 0) resp.code = MOD_ZERO;
                else resp.result = req.x % req.y;
            }
            break;
        default:
            resp.code = OTHER_OPER;
            break;
        }

        return resp;
    }

    std::string Calculator(std::string& package)
    {
        // 1. 服务器接收到数据包，先解析报文
        std::string content;
        bool r = Decode(package, &content);    
        if(!r) return "";

        // 2. 再对数据做反序列化
        Request req;
        r = req.Deserialization(content);
        if(!r) return "";

        // 3. 计算
        content = "";
        Response resp = CalculatorHandler(req);

        // 4. 数据序列化
        resp.Serialization(&content);
        content = Encode(content);

        return content;
    }

    ~ServerCal() {}
};